import ReactDOM from 'react-dom'
import { useState, useEffect } from 'react'

type Props = {
  count: number
}

const Child = ({ count }: Props) => {
  // 使用useEffect进行dom操作
  useEffect(() => {
    console.log('2 run effect')
    document.title = `当前游戏次数 ${count}`
  }, [count])

  // 解绑事件
  useEffect(() => {
    const hadleResize = () => {
      console.log('浏览器窗口大小变了')
    }
    window.addEventListener('resize', hadleResize)
    return () => {
      console.log('Child 组件卸载了')

      window.removeEventListener('resize', hadleResize)
    }
  }, [])
  return <h1>剩余机会：{3 - count}</h1>
}

const Counter = () => {
  const [count, setCount] = useState(0)
  const onClick = () => {
    setCount(count + 1)
  }
  return (
    <div>
      {count >= 3 ? '游戏失败' : <Child count={count}></Child>}
      <button onClick={onClick}>玩一次</button>
    </div>
  )
}

ReactDOM.render(<Counter />, document.getElementById('root'))
